package com.keyboardr.gamerater.task;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;

import com.keyboardr.gamerater.interfaces.GroupContainer;
import com.keyboardr.gamerater.model.Group;

import android.os.AsyncTask;

public class LoadFileTask extends AsyncTask<File, Void, ArrayList<Group>> {

	private final GroupContainer mContainer;

	public LoadFileTask(GroupContainer container) {
		mContainer = container;
	}

	@Override
	protected ArrayList<Group> doInBackground(File... file) {
		FileInputStream fIn = null;
		InputStreamReader isr = null;
		BufferedReader reader = null;
		String str = null;

		try {
			fIn = new FileInputStream(file[0]);
			isr = new InputStreamReader(fIn);
			reader = new BufferedReader(isr);
			StringBuilder buf = new StringBuilder();

			while ((str = reader.readLine()) != null) {
				buf.append(str + "\n");
			}

			str = buf.toString();

			fIn.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		ArrayList<Group> groups = null;
		try {
			JSONArray jArray = new JSONArray(str);
			groups = new ArrayList<Group>();
			for (int i = 0; i < jArray.length(); i++) {
				groups.add(new Group(jArray.getJSONObject(i)));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return groups;
	}

	@Override
	protected void onPostExecute(ArrayList<Group> result) {
		for (Group group : result) {
			mContainer.addGroup(group);
		}
	}

}
